package com.aero.cojbackendcommentservice.service.impl;

import com.aero.cojbackendcommentservice.mapper.ReplyMapper;
import com.aero.cojbackendcommentservice.service.ReplyService;
import com.aero.cojbackendcommon.common.ErrorCode;
import com.aero.cojbackendcommon.constant.CommonConstant;
import com.aero.cojbackendcommon.exception.BusinessException;
import com.aero.cojbackendcommon.exception.ThrowUtils;
import com.aero.cojbackendcommon.utils.SqlUtils;
import com.aero.cojbackendmodel.model.dto.reply.ReplyQueryRequest;
import com.aero.cojbackendmodel.model.entity.Reply;
import com.aero.cojbackendmodel.model.entity.User;
import com.aero.cojbackendmodel.model.vo.ReplyVO;
import com.aero.cojbackendmodel.model.vo.UserVO;
import com.aero.cojbackendserviceclient.service.UserFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Aero
 * @description 针对表【reply(回复)】的数据库操作Service实现
 */
@Service
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply>
        implements ReplyService {


    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 校验题目是否合法
     *
     * @param reply
     * @param add
     */
    @Override
    public void validReply(Reply reply, boolean add) {
        if (reply == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String content = reply.getContent();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(content), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param replyQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Reply> getQueryWrapper(ReplyQueryRequest replyQueryRequest) {
        QueryWrapper<Reply> queryWrapper = new QueryWrapper<>();
        if (replyQueryRequest == null) {
            return queryWrapper;
        }
        Long id = replyQueryRequest.getId();
        Long userId = replyQueryRequest.getUserId();
        String content = replyQueryRequest.getContent();
        Long questionId = replyQueryRequest.getQuestionId();
        Long commentId = replyQueryRequest.getCommentId();
        long current = replyQueryRequest.getCurrent();
        long pageSize = replyQueryRequest.getPageSize();
        String sortField = replyQueryRequest.getSortField();
        String sortOrder = replyQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq("commentId", commentId);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDeleted", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public ReplyVO getReplyVO(Reply reply, HttpServletRequest request) {
        ReplyVO replyVO = ReplyVO.objToVo(reply);
        return replyVO;
    }

    @Override
    public Page<ReplyVO> getReplyVOPage(Page<Reply> replyPage, HttpServletRequest request) {
        User loginUser = userFeignClient.getLoginUser(request);
        List<Reply> replyList = replyPage.getRecords();
        Page<ReplyVO> replyVOPage = new Page<>(replyPage.getCurrent(), replyPage.getSize(), replyPage.getTotal());
        if (CollectionUtils.isEmpty(replyList)) {
            return replyVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = replyList.stream().map(Reply::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userFeignClient.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<ReplyVO> replyVOList = replyList.stream().map(reply -> {
            ReplyVO replyVO = ReplyVO.objToVo(reply);
            Long userId = reply.getUserId();
            Long parentReplyId = reply.getParentReplyId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            UserVO userVO = userFeignClient.getUserVO(user);
            replyVO.setUserVO(userVO);
            User byId = userFeignClient.getById(parentReplyId);
            String userName = byId.getUserName();
            replyVO.setReplyUserName(userName);
            return replyVO;
        }).collect(Collectors.toList());
        replyVOPage.setRecords(replyVOList);
        return replyVOPage;
    }


}




